package com.coda.clouddisk.utils;

import java.lang.reflect.Field;
import java.util.Map;

public class MapToEntity {

    public static <T> T convertMapToObject(Map<String, Object> map, Class<T> clazz) throws Exception {
        T instance = clazz.getDeclaredConstructor().newInstance();
        setFields(instance, map);
        return instance;
    }

    private static void setFields(Object instance, Map<String, Object> map) throws Exception {
        Class<?> clazz = instance.getClass();

        while (clazz != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();

                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    field.set(instance, fieldValue);
                } catch (NoSuchFieldException e) {
                    // 如果当前类没有该字段，继续检查父类
                }
            }
            clazz = clazz.getSuperclass();
        }
    }
}
